package userInterface;
import dataProces.DatabaseOperations;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ChangePassword extends JDialog implements ActionListener {
    JPanel[] jPanels = new JPanel[4];
    String[] prompt = { "旧密码", "新密码", "确认密码" ,"修改", "返回","修改密码"};
    JButton[] jButtons = new JButton[2];
    JPasswordField[] jFields = new JPasswordField[3];
    public ChangePassword() {
        Container container = this.getContentPane();
        container.setLayout(new GridLayout(6, 1));
        for (int i = 0; i < jPanels.length; i++) {
            jPanels[i] = new JPanel();
            if (i < 3) {
                jPanels[i].add(new JLabel(prompt[i]));
                jFields[i] = new JPasswordField(15);
                jPanels[i].add(jFields[i]);
            } else
                for (int j = 0; j < jButtons.length; j++) {
                    jButtons[j] = new JButton(prompt[i+j]);
                    jButtons[j].addActionListener(this);
                    jPanels[i].add(jButtons[j]);
                }
            container.add(jPanels[i]);
        }
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(500, 300);
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation((screen.width - 500) / 2, (screen.height - 300) / 2);
        setTitle(prompt[5]);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jButtons[0]) {
            DatabaseOperations dOperations=new DatabaseOperations();
            String password=new String(jFields[0].getPassword());
            if(password.equals(dOperations.dataQueries("user",Login.user,"password"))){
                password=new String(jFields[1].getPassword());
                if(password.equals(new String(jFields[2].getPassword()))){
                    dOperations.dataUpdates("user",Login.user,"password",password);
                    JOptionPane.showMessageDialog(null, "修改成功！");
                    dispose(); 
                    new Login(); 
                }else{
                    JOptionPane.showMessageDialog(null, "确认密码错误！\n请重新输入");
                }
            }else{
                JOptionPane.showMessageDialog(null, "密码错误！\n请重新输入");
            }
        } else if (e.getSource() == jButtons[1]) {
            dispose();
            new UserMenu();
        }
    }

    public static void main(String[] args) {
        new ChangePassword();
    }
}
